//
//  AppDelegate.m
//  MountEverestFM
//
//  Created by ChenNing on 15/10/28.
//  Copyright © 2015年 chenn. All rights reserved.
//

#import "AppDelegate.h"
#import "TabbarViewController.h"
#import "FindViewController.h"
#import "SortViewController.h"
#import "PlayerViewController.h"
#import "SearchViewController.h"
#import "SetViewController.h"
#import "STKAudioPlayer.h"
#import "UIAlertTool.h"
#import <MediaPlayer/MediaPlayer.h>
#import "Player.h"
#import "LeadPageViewController.h"
#import "PlayerModel.h"
#import "MusicModel.h"
@interface AppDelegate ()
@property (nonatomic ,strong)NSString *statusStr;
@property (nonatomic, strong)LeadPageViewController *leadPage;
@property (nonatomic, strong)UINavigationController *findNavi;
@property (nonatomic, strong)TabbarViewController *fmTBC;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    
    
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
     *  在将生成的AppKey传入到此方法中。
     *  方法中的第二个参数用于指定要使用哪些社交平台，以数组形式传入。第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    [ShareSDK registerApp:@"c0931c27eb90"
          activePlatforms:@[
                            @(SSDKPlatformTypeWechat)]
                 onImport:^(SSDKPlatformType platformType){
                     switch (platformType)
                     {
                         case SSDKPlatformTypeSinaWeibo:
                             [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                             break;
                         case SSDKPlatformTypeWechat:
                             [ShareSDKConnector connectWeChat:[WXApi class]];
                             break;
                         default:
                             break;
                     }
                 }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
              
              switch (platformType)
              {
                  case SSDKPlatformTypeSinaWeibo:
                      //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                      [appInfo SSDKSetupSinaWeiboByAppKey:@"2980201786"
                                                appSecret:@"6b965a0c3fb89906232ba403b7647fad"
                                              redirectUri:@"https://api.weibo.com/oauth2/default.html"
                                                 authType:SSDKAuthTypeBoth];
                      break;
                  case SSDKPlatformTypeWechat:
                      // 设置微信
                      [appInfo SSDKSetupWeChatByAppId:@"wx22db73f7add9a9df"
                                            appSecret:@"d4624c36b6795d1d99dcf0547af5443d"];
                      break;
                  default:
                      break;
              }
          }];

    
    // 发现
    FindViewController *findVC = [[FindViewController alloc] init];
    findVC.title = @"发现";
    UIImage *imageFind=[UIImage imageNamed:@"icon_home_h@2x.png"];
    findVC.tabBarItem.image=imageFind;
    self.findNavi = [[UINavigationController alloc] initWithRootViewController:findVC];
    
    // 分类
    SortViewController *sortVC = [[SortViewController alloc] init];
    sortVC.title = @"分类";
    UIImage *imageSort=[UIImage imageNamed:@"toolbar_playinglist_h_p@3x.png"];
    sortVC.tabBarItem.image=imageSort;
    UINavigationController *sortNavi = [[UINavigationController alloc] initWithRootViewController:sortVC];
    
    // 播放器
    PlayerViewController *playerVC = [[PlayerViewController alloc]init];
    playerVC.tabBarItem.image = [UIImage imageNamed:@"tabbar_np_normal@2x.png"];
    UINavigationController *playerNavi = [[UINavigationController alloc]initWithRootViewController:playerVC];
    
    // 搜索
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.title = @"搜索";
    UIImage *imageSeach=[UIImage imageNamed:@"icon_search_h@2x.png"];
    searchVC.tabBarItem.image=imageSeach;
    UINavigationController *searchNavi = [[UINavigationController alloc] initWithRootViewController:searchVC];
    
    // 设置
    SetViewController *setVC = [[SetViewController alloc] init];
    setVC.title = @"设置";
    UIImage *imageSet=[UIImage imageNamed:@"icon_setting_n@2x.png"];
    setVC.tabBarItem.image=imageSet;
    UINavigationController *setNavi = [[UINavigationController alloc] initWithRootViewController:setVC];
    
    // TabBar
    NSArray *tabBarArr = [NSArray arrayWithObjects:_findNavi,sortNavi,playerNavi,searchNavi,setNavi, nil];
    self.fmTBC = [[TabbarViewController alloc] init];
    _fmTBC.viewControllers = tabBarArr;
    
    
    
    // NSUserDefaults 是单例 可以永久保存数据 可自由传递
    NSUserDefaults *userLoader = [NSUserDefaults standardUserDefaults];
    // 判断是否为第一次登陆
    if ([userLoader objectForKey:@"isFirstUse"] == nil) {
        // 如果是第一次,创建单例
        [userLoader  setObject:@"yes" forKey:@"isFirstUse"];
       
        self.leadPage = [[LeadPageViewController alloc]init];
        self.window.rootViewController = _leadPage;
        [_leadPage.enter addTarget:self action:@selector(enterAction) forControlEvents:UIControlEventTouchUpInside];
    } else {
        // 根视图控制器
        self.window.rootViewController = _fmTBC;
    }
   

    // 创建一个保存收藏数据的表
    DBHandler *dbHandler = [DBHandler shareInstance];
    // 打开数据库
    [dbHandler openDB];
    // 创建表收藏表
    [dbHandler createTable1];
    [dbHandler createTable2];
    [dbHandler createTableSearch];
    // 关闭数据库
    [dbHandler closeDB];
    

//    // 网络请求指示器
//    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self network];
    return YES;
}

- (void)enterAction
{
    self.window.rootViewController = self.fmTBC;
}

- (void)network
{
    // 开启网络监听器
    AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [afNetworkReachabilityManager startMonitoring];
    
    [afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无网络");
                self.statusStr = @"无网络";
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI网络");
                self.statusStr = @"WIFI网络";
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝数据");
                self.statusStr = @"蜂窝数据";
                break;
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络类型");
                self.statusStr =@"未知网络类型";
                break;
            default:
                break;
        }
        // 设置动画
        [self alert];
    }];
}

/////
-(void)alert
{

}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(receiveNotification:) name:@"isPlaying" object:nil];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)receiveNotification:(NSNotification *)noti
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    Player *player = [Player shareInstance];
    if (player.history == NO) {
        PlayerModel *playerModel = noti.object;
        MusicModel *musicModel = [playerModel.musicArray objectAtIndex:playerModel.index];
        [dic setObject:playerModel.title forKey:MPMediaItemPropertyAlbumTitle];
        
        [dic setObject:musicModel.title forKey:MPMediaItemPropertyTitle];
        
        NSURL *imageUrl = [NSURL URLWithString:musicModel.coverLarge];
        NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
        UIImage *image = [[UIImage alloc]initWithData:imageData];
        
        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
        [dic setObject:artwork forKey:MPMediaItemPropertyArtwork];
        
        [dic setObject:playerModel.nickname forKey:MPMediaItemPropertyArtist];
    } else {
        HistoryModel *historyModel = noti.object;
        [dic setObject:historyModel.albumTitle forKey:MPMediaItemPropertyAlbumTitle];
        
        [dic setObject:historyModel.title forKey:MPMediaItemPropertyTitle];
        
        NSURL *imageUrl = [NSURL URLWithString:historyModel.coverLarge];
        NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
        UIImage *image = [[UIImage alloc]initWithData:imageData];
        
        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
        [dic setObject:artwork forKey:MPMediaItemPropertyArtwork];
        
        [dic setObject:historyModel.nickname forKey:MPMediaItemPropertyArtist];
    }
 

    
    [[MPNowPlayingInfoCenter defaultCenter]setNowPlayingInfo:dic];
    
    

}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    Player *player = [Player shareInstance];
    [player collectPreseve];
}




@end
